<template>
  <el-card>
    <div slot="header" class="clearfix">
      <span>广告订单</span>
    </div>
    <div class="home-container">
      <div class="subtitle">
        快捷筛选:
        <el-button :type="index[0]?'primary':''" size="mini" @click="quickFilter(0)">未收款</el-button>
        <el-button :type="index[1]?'primary':''" size="mini" @click="quickFilter(1)">未填开票号</el-button>
        <el-button :type="index[2]?'primary':''" size="mini" @click="quickFilter(2)">今日发文
        </el-button>
      </div>

      <v-searchForm
        :form-data="filter_info"
        :form-title="formTitle"
        @search="search"
        @reset="reset"
      />
      <v-tableBtns
        :show-upload="financeRole"
        :table-title="exportTitle"
        :table-data="exportData"
        :on-export="handleExport"
        :upload-url="uploadUrl"
        title="广告订单"
      />
      <v-table
        ref="table"
        :table-title="tableTitle"
        :table-data="tableData"
        :deletable="financeRole"
        :header-cell-style="changeStyle"
        @sortChange="sortChange"
        @del="del"
        @edit="edit"
      />
      <v-pagination
        :page-info="pageInfo"
        :get-table-list="getTableList"
      />

    </div>
  </el-card>
</template>

<script>
  import {mapGetters} from 'vuex'
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import {parseTime} from '../../../utils'
  import auth from '@/mixins/auth'
  import {$get} from '@/utils/newRequest'
  const exp_list = [
          {
            cn: 'id',
            en: 'ad_id'
          },
          // {
          //   cn: '公司主体',
          //   en: 'ct_name'
          // },
          {
            cn: '公众号',
            en: 'name'
          },
          {
            cn: '广告主类型',
            en: 'advertiser_type'
          },
          {
            cn: '实际广告主',
            en: 'ad_name'
          },
          {
            cn: '品牌名',
            en: 'brand'
          },
          {
            cn: '短视频/直播',
            en: 'media_type',
          },
          {
            cn: '星图/代下单',
            en: 'order_form',
          },
          {
            cn: '公众号分组',
            en: 'groups_name'
          },
          {
            cn: '广告类型',
            en: 'ad_type'
          },
          // {
          //   cn: '返点比例',
          //   en: 'return_point',
          // },
          {
            cn: '返点金额',
            en: 'return_point_price',
          },
          {
            cn: '财务返点金额',
            en: 'financial_rebate_amount',
          },
          {
            cn: '返点支付银行',
            en: 'rebate_payment_bank',
          },
           {
            cn: '返点支付日期',
            en: 'rebate_payment_date',
          },
          // {
          //   cn: '对私返点',
          //   en: 'private_return_point',
          // },
          // {
          //   cn: '支付时间',
          //   en: 'payment_date_point',
          // },
          // {
          //   cn: '分销佣金比例',
          //   en: 'fenxiao',
          // },
          // {
          //   cn: '链接佣金比例',
          //   en: 'yongjin',
          // },
          {
            cn: '广告主(合同主体)',
            en: 'bill_company'
          },
          {
            cn: '广告位置',
            en: 'ad_place_name'
          },
          {
            cn: '外采实际支付金额',
            en: 'actual_amount_outsourcing',
          },
          {
            cn: '外采付款银行',
            en: 'paying_bank',
          },
          {
            cn: '外采付款日期',
            en: 'date_payment',
          },
          {
            cn: '外采供应商',
            en: 'supplier'
          },
          {
            cn: '广告价格',
            en: 'ad_price'
          },
          {
            cn: '折后金额',
            en: 'amount_discount'
          },
          {
            cn: '发布时间',
            en: 'publish_at'
          },




          // {
          //   cn: '是否预订',
          //   en: 'is_book'
          // },
          // {
          //   cn: '是否开具发票',
          //   en: 'is_bill'
          // },
          {
            cn: '开票日期',
            en: 'bill_at'
          },
          {
            cn: '发票号(微赞)',
            en: 'bill_num'
          },
          {
            cn: '收款银行(微赞)',
            en: 'receive_bank'
          },
          {
            cn: '收款帐户(微赞)',
            en: 'receive_account'
          },
          {
            cn: '收款日期(微赞)',
            en: 'receive_at'
          },
          {
            cn: '收款金额(微赞)',
            en: 'real_price'
          },
          {
            cn: '发票号(微莱)',
            en: 'wl_bill_num'
          },
          {
            cn: '开票公司(微莱)',
            en: 'wl_bill_company'
          },
          {
            cn: '收款银行(微莱)',
            en: 'wl_receive_bank'
          },
          {
            cn: '收款帐户(微莱)',
            en: 'wl_receive_account'
          },
          {
            cn: '收款日期(微莱)',
            en: 'wl_receive_at'
          },
          {
            cn: '收款金额(微莱)',
            en: 'wl_real_price'
          },

           {
            cn: '收款银行(返点)',
            en: 'receiving_bank_rebate'
          },
          // {
          //   cn: '收款帐户(返点)',
          //   en: 'collection_account_rebate'
          // },
          {
            cn: '收款日期(返点)',
            en: 'collection_date_rebate'
          },
          {
            cn: '收款金额(返点)',
            en: 'collection_amount_rebate'
          },
          // {
          //   cn: '订单号',
          //   en: 'ad_order'
          // },
          {
            cn: '提交人',
            en: 'fans_name'
          },
          // {
          //   cn: '是否签合同',
          //   en: 'is_contract'
          // },
          // {
          //   cn: '合同号',
          //   en: 'contract_num'
          // },
          {
            cn: '备注',
            en: 'remark'
          },
          // {
          //   cn: '备注(数据查询系统)',
          //   en: 'data_query'
          // },
          // {
          //   cn: '收款银行',
          //   en: 'bank_name'
          // },
          {
            cn: '采购成本（含税价）',
            en: 'purchase_cost'
          },
          {
            cn: '供应商名称',
            en: 'supplier_name'
          },
               {
            cn: '返点收入',
            en: 'rebate_income'
          },
          // {
          //   cn: '是否原创',
          //   en: '是否原创'
          // },
          // {
          //   cn: '编辑负责人',
          //   en: '编辑负责人'
          // },
          {
            cn: '创建时间',
            en: 'created_at'
          },
          // {
          //   cn: '设计负责人',
          //   en: '设计负责人'
          // },
          // {
          //   cn: '摄影负责人',
          //   en: '摄影负责人'
          // },
          {
            cn: '商务人员',
            en: 'swname'
          },
          {
            cn: '商务助理',
            en: 'xmname'
          },
          {
            cn: '广告项目',
            en: 'advertising_project',
          },
              {
            cn: '项目起始日期',
            en: 'start_date'
          },

          {
            cn: '项目终止日期',
            en: 'end_date'
          },
          {
            cn: '账期到期时间',
            en: 'settlement_date'
          },


          {
            cn: '我方公司合同主体',
            en: 'subject_of_contract'
          },
        ]

  export default {
    name: 'Home',
    mixins: [auth],
    components: {UploadExcelComponent},
    exp_list,
    data() {
      const now = new Date();
      now.setTime(now.getTime() - 3600 * 1000 * 24 * (now.getDate() - 1));
      const startTime = parseTime(now, '{y}-{m}-{d}');
      const endTime = parseTime(new Date(now.getFullYear(),now.getMonth()+1,0),'{y}-{m}-{d}')

      return {
        uploadUrl: process.env.BASE_API + 'action/WechatAdvs/saveFile',
        index: [false, false, false],
        formTitle: [
          {
            cn: '订单id：',
            en: 'ad_id'
          },
          {
            cn: '实际广告主：',
            en: 'ad_name'
          },
          {
            cn: '公众号：',
            en: 'name'
          },
          {
            cn: '商务：',
            en: 'swname',
            placeholder: '输入全称'
          },
          {
            cn: '收款状态：',
            en: 'is_receive',
            type: 'select',
            list: [
              {
                label: '未收款',
                value: 0
              },
              {
                label: '已收款',
                value: 2
              }
            ]
          },
          // {
          //   cn: '合同编号：',
          //   en: 'contract_num',
          //   type: 'select',
          //   list: [
          //     {
          //       label: '有',
          //       value: 1
          //     },
          //     {
          //       label: '无',
          //       value: 0
          //     }
          //   ]
          // },
          {
            cn: '是否开票：',
            en: 'is_bill',
            type: 'select',
            list: [
              {
                label: '是',
                value: 1
              },
              {
                label: '否',
                value: 0
              }
            ]
          },
          {
            cn: '发布时间：',
            en: 'created_at',
            type: 'time'
          },
          {
            cn: '项目起始日期',
            en: 'start_date',
            type: 'time'

          },

          {
            cn: '项目终止日期',
            en: 'end_date',
            type: 'time'
          },

          {
            cn: '账期到期时间',
            en: 'settlement_date',
            type: 'time'
          },

        ],
        filter_info: {
          created_at: [startTime, endTime]
        },
        originFilter: {
          created_at: [startTime, endTime]
        },
        tableTitle: [
          {
            cn: 'id',
            en: 'ad_id',
            width: '80px',
            sortable: true
          },
          {
            cn: '公众号',
            en: 'name',
            sortable: true
          },
          {
            cn: '版位',
            en: 'ad_place_name'
          },
          {
            cn: '我方公司合同主体',
            en: 'subject_of_contract'
          },
          {
            cn: '发布时间',
            en: 'publish_at',
            sortable: true
          },
          {
            cn: '项目起始日期',
            en: 'start_date',
            sortable: true
          },
          {
            cn: '项目终止日期',
            en: 'end_date',
            sortable: true
          },
         {
            cn: '账期到期时间',
            en: 'settlement_date',
            sortable: true
          },


          {
            cn: '实际广告主',
            en: 'ad_name'
          },
          {
            cn: '品牌名',
            en: 'brand'
          },
          {
            cn: '金额',
            en: 'ad_price',
            sortable: true
          },
          {
            cn: '微赞收款',
            en: 'real_price',
            sortable: true
          },
          {
            cn: '微萊收款',
            en: 'wl_real_price',
            sortable: true
          },
          {
            cn: '商务',
            en: 'swname',
            sortable: true
          },
          {
            cn: '提交人',
            en: 'fans_name'
          },
          {
            cn: '创建时间',
            en: 'created_at',
            width: '180px',
            sortable: true
          },
          // {
          //   cn: '开票状态',
          //   en: 'invoice_state'
          // }
        ],
        tableData: [],

        // 排序
        sidx: 'publish_at',
        sortKey: null,

        exportTitle :  exp_list,
        exportData: [],
        // f分页
        pageInfo: {
          pageNumber: 1,
          pageSize: 30,
          totalPage: 0,
          totalRow: 0
        }
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'roles'
      ]),
      filter_infos() {
        const data = {}
        const origin = this.filter_info
        for (const key in origin) {
          if (!this.filter_info[key] && this.filter_info[key] !== 0) {
            this.$delete(this.filter_info, key)
            continue
          }
          if (key === 'created_at') {
            data.start_time = origin[key][0]
            data.End_time = origin[key][1]
          }else if (key === 'start_date') {
            data.start_date_s = origin[key][0]
            data.start_date_e = origin[key][1]
          }else if (key === 'end_date') {
            data.end_date_s = origin[key][0]
            data.end_date_e = origin[key][1]
          }else if (key === 'settlement_date') {
            data.settlement_date_s = origin[key][0]
            data.settlement_date_e = origin[key][1]
          }else {
            data[key] = origin[key]
          }
        }
        if (!origin.created_at) {
          delete data.start_time
          delete data.End_time
        }
        return data
      }
    },
    watch: {
      'filter_info.is_receive'(val) {
        console.log(val);
        if (val === 0) {
          this.$set(this.index, 0, true)
        } else {
          this.$set(this.index, 0, false)
        }
      },
      'filter_info.is_bill'(val) {
        if (val === 0) {
          this.$set(this.index, 1, true)
        } else {
          this.$set(this.index, 1, false)
        }
      },
      'filter_info.created_at'(val, val2) {
        let todayTime = parseTime(new Date(), '{y}-{m}-{d}');
        if (val && val[0] === todayTime && val[1] === todayTime) {
          this.$set(this.index, 2, true)
        } else {
          this.$set(this.index, 2, false)
        }

      }
    },
    activated() {
      this.getTableList()
    },
    methods: {
      changeStyle({row, column, rowIndex, columnIndex}) {
        console.log(row, column, rowIndex, columnIndex)
      },
      getTableList() {
        const loading = this.$loading()
        console.dir(this.$get)
        const datas = {
          ...this.filter_infos,
          page: this.pageInfo.pageNumber, rows: this.pageInfo.pageSize,
          sidx: this.sidx,
          sortKey: this.sortKey,
          type: 0
        }
        this.$get('action/WechatAdvs/dataGrid', datas)
          .then(res => {
            let list
            const data = res.data
            if (data.list && data.list.length) {
              list = data.list.map((item, index) => {
                switch (item.invoice_state) {
                  case 0:
                    item.invoice_state = '未开票'
                    break
                  case 1:
                    item.invoice_state = '开票中'
                    break
                  case 2:
                    item.invoice_state = '已开票'
                    break
                }
                return item
              })
            }
            this.pageInfo.totalPage = data.totalPage
            this.pageInfo.totalRow = data.totalRow

            this.tableData = list || []
              loading.close()
          })
          .catch(err => {
            loading.close()
            this.$message({
              message: '获取数据失败',
              type: 'error'
            })
          })
      },
      // 搜索
      search() {
        this.pageInfo.pageNumber=1
        this.getTableList()
      },
      quickFilter(index) {
        let data
        this.index[index] = !this.index[index]
        switch (index) {
          case 0:
            if (this.index[index]) {
              this.$set(this.filter_info, 'is_receive', 0)
            } else {
              this.$set(this.filter_info, 'is_receive')
            }
            break
          case 1:
            if (this.index[index]) {
              this.$set(this.filter_info, 'is_bill', 0)
            } else {
              this.$set(this.filter_info, 'is_bill')
            }
            break
          case 2:
            if (this.index[index]) {
              const newDate = new Date()
              const date = parseTime(newDate, '{y}-{m}-{d}')

              this.$set(this.filter_info, 'created_at', [date, date])
            } else {
              this.$set(this.filter_info, 'created_at', this.originFilter.created_at)
            }
        }
        this.pageInfo = {
          pageNumber: 1,
          pageSize: 30,
          totalPage: 0,
          totalRow: 0
        }
        this.getTableList()
      },
      reset() {
        this.filter_info = {}
        this.index = []
        this.getTableList()
      },

      del(val) {
        const data = {ad_id: val.row.ad_id}
        this.$post('action/WechatAdvs/del', data)
          .then(res => {
            this.getTableList()
            this.$message({
              message: res.msg,
              type: 'success'
            })
          })
          .catch(_ => {

          })
      },
      upload() {
        this.$router.push({
          name: 'adv_order.upload'
        })
      },

      edit(val) {
        this.$router.push({
          name: 'adv_order.order_info',
          query: {id: val.row.ad_id}
        })
      },
      addnew() {
        console.log(1)
      },
         // handleExport(){
         //     exp_handle(0)
         // }
        // ,
      handleExport() {
        $get('action/WechatAdvs/dataList', {type: 0, sidx: 'publish_at', ...this.filter_infos})
          .then(res => {
            new Promise((resolve, reject) => {
              let datas = res.data;
              let list = datas.map((item, index) => {
                const obj = item
                obj.is_bill = item.is_bill ? '是' : '否';
                obj.is_book = item.is_book ? '是' : '否';
                obj.is_contract = item.is_contract ? '是' : '否';
                obj.return_point = obj.return_point?(obj.return_point+'%'):''
                obj.private_return_point = obj.private_return_point?(obj.private_return_point+'%'):''
                obj.subsidiary_point = obj.subsidiary_point?(obj.subsidiary_point+'%'):''
                if  (item.groups_name == '城觅抖音'){
                 obj.media_type = item.media_type ? '直播' : '短视频';
                 obj.order_form = item.order_form
                 // obj.order_form = item.order_form ? '代下单' : '星图下单';
                }
                else{
                 obj.media_type = '';
                 obj.order_form = '';
                 }
                switch (item.subsidiary_type) {
                  case 0:
                    obj.fenxiao = obj.subsidiary_point;
                    obj.yongjin = '';
                    break;
                  case 1:
                    obj.fenxiao = '';
                    obj.yongjin = obj.subsidiary_point;
                    break;
                  default:
                    obj.fenxiao = '';
                    obj.yongjin = '';
                    break;
                }
                try {
                  const extend = item.extend && JSON.parse(item.extend)
                  extend && extend.forEach(item => {
                    obj[item.label_name] = item.value
                  })
                } catch (e) {
                  //订单号3129返回的extend字段不完整
                  return obj
                }
                return obj
              })
              resolve(list)
            }).then(list => {
              this.exportData = list || []
            }).catch(err => {
              this.exportData = []
            })
          }).catch(_ => {
          this.$message({
            message: '导出超时',
            type: 'error'
          })
          this.exportData = []

        })
      },
      // 排序
      sortChange({column, prop, order}) {
        this.sidx = prop || 'publish_at'
        this.sortKey = order === 'ascending' ? 'asc' : null
        this.getTableList()
      }

    }

  }
</script>

<style rel="stylesheet/scss" lang="scss">

</style>
